package com.omronservice.web.webscoket;

import com.omronservice.web.scheduled.ScheduledTask;
import com.omronservice.web.webscoket.bean.BaseWebsocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 上料机
 */
@ServerEndpoint("/GetLDHSParams/{line}/{index}")
@Component
public class ChargingWebsocket extends BaseWebsocket{

    public static int onlineCount = 0;

    public final static List<ChargingWebsocket> webSocketSet = new ArrayList<>();

    private Session session;

    private static final Logger log = LoggerFactory.getLogger(ChargingWebsocket.class);



    @OnOpen
    public void onOpen (@PathParam(value="line") String line,@PathParam(value="index") String index, Session session){
        this.session = session;
        this.productionLine = line;
        this.productionNo = index;
        webSocketSet.add(this);
        addOnlineCount();
        ScheduledTask.temp = 1;
        System.out.println("MyWebsocket2有新链接加入!当前在线人数为" + getOnlineCount()+"========="+line+"====="+index);
        log.info(className+getOnlineCount());
    }

    @OnClose
    public void onClose (){
        webSocketSet.remove(this);
        subOnlineCount();
        System.out.println("GetLDHSParams有一链接关闭!当前在线人数为" + getOnlineCount());
    }

    @OnMessage
    public void onMessage (String message, Session session) throws IOException {
        System.out.println("GetLDHSParams来自客户端的消息:" + message);
        // 群发消息
        for ( ChargingWebsocket item : webSocketSet ){
            item.sendMessage(message+"223232");
        }
    }

    public void sendMessage (String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public boolean isOpen(){
        return this.session.isOpen();
    }



    public static synchronized  int getOnlineCount (){
        return ChargingWebsocket.onlineCount;
    }

    public static synchronized void addOnlineCount (){
        ChargingWebsocket.onlineCount++;
    }

    public static synchronized void subOnlineCount (){
        ChargingWebsocket.onlineCount--;
    }

}